package com.zenithmind.document.pojo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 文档权限创建DTO
 * 遵循单一职责原则：专注于权限创建数据传输
 * 遵循开闭原则：通过验证注解支持扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档权限创建DTO")
public class DocumentPermissionCreateDTO {

    @Schema(description = "文档ID", required = true, example = "doc123456")
    @NotBlank(message = "文档ID不能为空")
    private String documentId;

    @Schema(description = "目标类型", required = true, example = "USER", allowableValues = {"USER", "ROLE", "GROUP", "DEPARTMENT"})
    @NotBlank(message = "目标类型不能为空")
    private String targetType;

    @Schema(description = "目标ID", required = true, example = "user123456")
    @NotBlank(message = "目标ID不能为空")
    private String targetId;

    @Schema(description = "目标名称", example = "张三")
    private String targetName;

    @Schema(description = "权限类型", required = true, example = "READ", allowableValues = {"READ", "write", "delete", "share", "admin"})
    @NotBlank(message = "权限类型不能为空")
    private String permissionType;

    @Schema(description = "权限值", required = true, example = "ALLOW", allowableValues = {"ALLOW", "DENY", "INHERIT"})
    @NotBlank(message = "权限值不能为空")
    private String permissionValue;

    @Schema(description = "权限级别", example = "1")
    private Integer permissionLevel;

    @Schema(description = "权限范围", example = "DOCUMENT", allowableValues = {"DOCUMENT", "FOLDER", "CATEGORY", "GLOBAL"})
    private String permissionScope;

    @Schema(description = "权限条件", example = "{\"timeRange\": \"09:00-18:00\", \"ipWhitelist\": [\"192.168.1.0/24\"]}")
    private String permissionCondition;

    @Schema(description = "是否继承", example = "true")
    private Boolean isInherited;

    @Schema(description = "父权限ID", example = "perm123456")
    private String parentPermissionId;

    @Schema(description = "优先级", example = "100")
    private Integer priority;

    @Schema(description = "生效时间", example = "2025-01-09T00:00:00")
    private LocalDateTime effectiveTime;

    @Schema(description = "过期时间", example = "2025-12-31T23:59:59")
    private LocalDateTime expirationTime;

    @Schema(description = "授权人ID", example = "admin123")
    private String grantorId;

    @Schema(description = "授权原因", example = "项目协作需要")
    private String grantReason;

    @Schema(description = "权限标签", example = "临时权限,项目相关")
    private String permissionTags;

    @Schema(description = "是否可委托", example = "false")
    private Boolean isDelegatable;

    @Schema(description = "最大委托层级", example = "2")
    private Integer maxDelegationLevel;

    @Schema(description = "委托限制", example = "{\"maxUsers\": 5, \"timeLimit\": \"7d\"}")
    private String delegationRestrictions;

    @Schema(description = "审批状态", example = "APPROVED", allowableValues = {"PENDING", "APPROVED", "REJECTED", "REVOKED"})
    private String approvalStatus;

    @Schema(description = "审批人ID", example = "approver123")
    private String approverId;

    @Schema(description = "审批时间", example = "2025-01-09T10:00:00")
    private LocalDateTime approvalTime;

    @Schema(description = "审批意见", example = "同意授权")
    private String approvalComment;

    @Schema(description = "权限描述", example = "允许查看和编辑项目文档")
    private String description;

    @Schema(description = "扩展属性", example = "{\"department\": \"IT\", \"project\": \"ProjectA\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "临时权限，项目结束后自动回收")
    private String remarks;

    /**
     * 创建用户读权限
     */
    public static DocumentPermissionCreateDTO createUserReadPermission(String documentId, String userId, String grantorId) {
        DocumentPermissionCreateDTO dto = new DocumentPermissionCreateDTO();
        dto.setDocumentId(documentId);
        dto.setTargetType("USER");
        dto.setTargetId(userId);
        dto.setPermissionType("READ");
        dto.setPermissionValue("ALLOW");
        dto.setPermissionLevel(1);
        dto.setPermissionScope("DOCUMENT");
        dto.setIsInherited(false);
        dto.setPriority(100);
        dto.setGrantorId(grantorId);
        dto.setIsDelegatable(false);
        dto.setApprovalStatus("APPROVED");
        return dto;
    }

    /**
     * 创建用户写权限
     */
    public static DocumentPermissionCreateDTO createUserWritePermission(String documentId, String userId, String grantorId) {
        DocumentPermissionCreateDTO dto = new DocumentPermissionCreateDTO();
        dto.setDocumentId(documentId);
        dto.setTargetType("USER");
        dto.setTargetId(userId);
        dto.setPermissionType("write");
        dto.setPermissionValue("ALLOW");
        dto.setPermissionLevel(2);
        dto.setPermissionScope("DOCUMENT");
        dto.setIsInherited(false);
        dto.setPriority(200);
        dto.setGrantorId(grantorId);
        dto.setIsDelegatable(false);
        dto.setApprovalStatus("APPROVED");
        return dto;
    }

    /**
     * 创建角色权限
     */
    public static DocumentPermissionCreateDTO createRolePermission(String documentId, String roleId, String permissionType, String grantorId) {
        DocumentPermissionCreateDTO dto = new DocumentPermissionCreateDTO();
        dto.setDocumentId(documentId);
        dto.setTargetType("ROLE");
        dto.setTargetId(roleId);
        dto.setPermissionType(permissionType);
        dto.setPermissionValue("ALLOW");
        dto.setPermissionLevel(getPermissionLevel(permissionType));
        dto.setPermissionScope("DOCUMENT");
        dto.setIsInherited(true);
        dto.setPriority(getPermissionPriority(permissionType));
        dto.setGrantorId(grantorId);
        dto.setIsDelegatable(false);
        dto.setApprovalStatus("APPROVED");
        return dto;
    }

    /**
     * 创建临时权限
     */
    public static DocumentPermissionCreateDTO createTemporaryPermission(String documentId, String userId, String permissionType, 
                                                                        LocalDateTime expirationTime, String grantorId) {
        DocumentPermissionCreateDTO dto = new DocumentPermissionCreateDTO();
        dto.setDocumentId(documentId);
        dto.setTargetType("USER");
        dto.setTargetId(userId);
        dto.setPermissionType(permissionType);
        dto.setPermissionValue("ALLOW");
        dto.setPermissionLevel(getPermissionLevel(permissionType));
        dto.setPermissionScope("DOCUMENT");
        dto.setIsInherited(false);
        dto.setPriority(getPermissionPriority(permissionType));
        dto.setEffectiveTime(LocalDateTime.now());
        dto.setExpirationTime(expirationTime);
        dto.setGrantorId(grantorId);
        dto.setIsDelegatable(false);
        dto.setApprovalStatus("APPROVED");
        dto.setPermissionTags("临时权限");
        return dto;
    }

    /**
     * 获取权限级别
     */
    private static Integer getPermissionLevel(String permissionType) {
        switch (permissionType.toLowerCase()) {
            case "read": return 1;
            case "write": return 2;
            case "delete": return 3;
            case "share": return 4;
            case "admin": return 5;
            default: return 1;
        }
    }

    /**
     * 获取权限优先级
     */
    private static Integer getPermissionPriority(String permissionType) {
        switch (permissionType.toLowerCase()) {
            case "read": return 100;
            case "write": return 200;
            case "delete": return 300;
            case "share": return 400;
            case "admin": return 500;
            default: return 100;
        }
    }

    /**
     * 验证DTO数据
     */
    public boolean isValid() {
        if (documentId == null || documentId.trim().isEmpty()) return false;
        if (targetType == null || targetType.trim().isEmpty()) return false;
        if (targetId == null || targetId.trim().isEmpty()) return false;
        if (permissionType == null || permissionType.trim().isEmpty()) return false;
        if (permissionValue == null || permissionValue.trim().isEmpty()) return false;
        
        // 验证时间范围
        if (effectiveTime != null && expirationTime != null) {
            return !effectiveTime.isAfter(expirationTime);
        }
        
        return true;
    }

    /**
     * 是否为临时权限
     */
    public boolean isTemporary() {
        return expirationTime != null && expirationTime.isAfter(LocalDateTime.now());
    }

    /**
     * 是否已过期
     */
    public boolean isExpired() {
        return expirationTime != null && expirationTime.isBefore(LocalDateTime.now());
    }

    /**
     * 是否已生效
     */
    public boolean isEffective() {
        LocalDateTime now = LocalDateTime.now();
        boolean afterEffective = effectiveTime == null || !effectiveTime.isAfter(now);
        boolean beforeExpiration = expirationTime == null || !expirationTime.isBefore(now);
        return afterEffective && beforeExpiration;
    }

    /**
     * 权限类型枚举
     */
    public enum PermissionType {
        READ("读取"),
        write("写入"),
        delete("删除"),
        share("分享"),
        admin("管理");

        private final String description;

        PermissionType(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    /**
     * 目标类型枚举
     */
    public enum TargetType {
        USER("用户"),
        ROLE("角色"),
        GROUP("用户组"),
        DEPARTMENT("部门");

        private final String description;

        TargetType(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    /**
     * 权限值枚举
     */
    public enum PermissionValue {
        ALLOW("允许"),
        DENY("拒绝"),
        INHERIT("继承");

        private final String description;

        PermissionValue(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }
}
